package com.whl.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

import com.google.common.io.Files;

public class FileUtils {

	public static String getFileName(String fileName) {
		int index = fileName.lastIndexOf('\\');
		if (index == -1) {
			index = fileName.lastIndexOf('/');
			if (index == -1) {
				return fileName;
			} else {
				return fileName.substring(index, fileName.length());
			}
		} else {
			return fileName.substring(index, fileName.length());
		}
	}

	public static String buildAbsolutePath(String path, String name) {
		return path + name;
	}

	public static String fileSurfix(String path) {
		int lastIndex = path.lastIndexOf(".");
		return lastIndex < 0 ? "" : path.substring(lastIndex + 1);
	}

	public static void saveFile(MultipartFile file, String path, boolean backup) {
		// 保存
		try {
			File targetFile = new File(path);
			if (targetFile.exists()) {
				if (backup) {
					backupFile(targetFile);
				} else {
					targetFile.delete();
				}
			} else {
				File parentFile = targetFile.getParentFile();
				if (!targetFile.exists()) {
					parentFile.mkdirs();
				}
			}
			file.transferTo(targetFile);
		} catch (Exception e) {
			throw new RuntimeException("保存文件出错", e);
		}
	}

	public static void backupFile(File targetFile) throws IOException {
		String path = targetFile.getAbsolutePath();
		String surfix = fileSurfix(path);
		String filePrePath = path.substring(0, path.length() - surfix.length());
		String curTime = DateFormatUtil.date2Str(new Date(), DateFormatUtil.yyyyMMddHHmmssSSS, false);
		String bakPath = filePrePath + curTime + "." + surfix;
		File bakFile = new File(bakPath);
		Files.move(targetFile, bakFile);
	}

	public static void addDownloadHeader(String displayName, HttpServletResponse response) {
		try {
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			String value = "attachment;filename=" + URLEncoder.encode(displayName, "UTF-8") + ";filename*=utf-8''"
					+ URLEncoder.encode(displayName, "UTF-8");
			response.addHeader("Content-Disposition", value);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static void addImageScanHeader(HttpServletResponse response) {
		response.setContentType("image/png");
	}

	public static void download(String filePath, String displayName, HttpServletResponse response) {
		addDownloadHeader(displayName, response);
		FileInputStream is = null;
		try {
			OutputStream os = response.getOutputStream();
			File file = new File(filePath);
			if (file.exists()) {// 判断文件是否存在
				is = new FileInputStream(file);
				byte[] buff = new byte[200 * 1024];
				int filelength = 0;
				while ((filelength = is.read(buff)) > 0) {
					os.write(buff, 0, filelength);
				}
				os.flush();
			} else {
				throw new RuntimeException(String.format("文件不存在[%s]", filePath));
			}

		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				throw new RuntimeException("关闭IO出错", e);
			}
		}
	}

}
